import weatherService from './weatherService.js';
import cacheService from './cacheService.js';

// 天气管理服务 - 整合API和缓存
class WeatherManager {
  constructor() {
    this.weatherService = weatherService;
    this.cacheService = cacheService;
  }

  /**
   * 获取天气信息（带缓存）
   * @param {string} cityName - 城市名称
   * @returns {Promise<Object>} 天气数据
   */
  async getWeather(cityName) {
    try {
      // 验证城市名称
      if (!this.weatherService.validateCityName(cityName)) {
        throw new Error('请输入有效的城市名称');
      }

      const trimmedCityName = cityName.trim();

      // 首先检查缓存
      const cachedData = this.cacheService.get(trimmedCityName);
      if (cachedData) {
        console.log(`从缓存获取 ${trimmedCityName} 的天气信息`);
        return {
          ...cachedData,
          fromCache: true
        };
      }

      // 缓存中没有，从API获取
      console.log(`从API获取 ${trimmedCityName} 的天气信息`);
      const weatherData = await this.weatherService.getWeatherByCity(trimmedCityName);
      
      // 将数据存入缓存
      this.cacheService.set(trimmedCityName, weatherData);
      
      return {
        ...weatherData,
        fromCache: false
      };
    } catch (error) {
      console.error('获取天气信息失败:', error);
      throw error;
    }
  }

  /**
   * 刷新天气信息（强制从API获取）
   * @param {string} cityName - 城市名称
   * @returns {Promise<Object>} 天气数据
   */
  async refreshWeather(cityName) {
    try {
      if (!this.weatherService.validateCityName(cityName)) {
        throw new Error('请输入有效的城市名称');
      }

      const trimmedCityName = cityName.trim();

      // 删除缓存
      this.cacheService.delete(trimmedCityName);

      // 从API获取最新数据
      const weatherData = await this.weatherService.getWeatherByCity(trimmedCityName);
      
      // 更新缓存
      this.cacheService.set(trimmedCityName, weatherData);
      
      return {
        ...weatherData,
        fromCache: false,
        refreshed: true
      };
    } catch (error) {
      console.error('刷新天气信息失败:', error);
      throw error;
    }
  }

  /**
   * 获取天气图标
   * @param {string} iconCode - 图标代码
   * @param {boolean} useLocal - 是否使用本地图标
   * @returns {string} 图标URL或emoji
   */
  getWeatherIcon(iconCode, useLocal = false) {
    if (useLocal) {
      // 从图标代码推断天气类型
      const weatherType = this.getWeatherTypeFromIcon(iconCode);
      return this.weatherService.getLocalWeatherIcon(weatherType);
    }
    return this.weatherService.getWeatherIconUrl(iconCode);
  }

  /**
   * 从图标代码获取天气类型
   * @param {string} iconCode - 图标代码
   * @returns {string} 天气类型
   */
  getWeatherTypeFromIcon(iconCode) {
    const iconMap = {
      '01': 'Clear',    // 晴天
      '02': 'Clouds',   // 少云
      '03': 'Clouds',   // 多云
      '04': 'Clouds',   // 阴天
      '09': 'Rain',     // 阵雨
      '10': 'Rain',     // 雨
      '11': 'Thunderstorm', // 雷雨
      '13': 'Snow',     // 雪
      '50': 'Mist'      // 雾
    };
    
    const iconPrefix = iconCode.substring(0, 2);
    return iconMap[iconPrefix] || 'Clear';
  }

  /**
   * 获取缓存统计信息
   * @returns {Object} 缓存统计
   */
  getCacheStats() {
    return this.cacheService.getStats();
  }

  /**
   * 获取已缓存的城市列表
   * @returns {Array<string>} 城市列表
   */
  getCachedCities() {
    return this.cacheService.getCachedCities();
  }

  /**
   * 清空缓存
   */
  clearCache() {
    this.cacheService.clear();
  }

  /**
   * 批量获取多个城市的天气信息
   * @param {Array<string>} cityNames - 城市名称数组
   * @returns {Promise<Array<Object>>} 天气数据数组
   */
  async getBatchWeather(cityNames) {
    const results = [];
    
    for (const cityName of cityNames) {
      try {
        const weather = await this.getWeather(cityName);
        results.push({
          success: true,
          cityName,
          data: weather
        });
      } catch (error) {
        results.push({
          success: false,
          cityName,
          error: error.message
        });
      }
    }
    
    return results;
  }

  /**
   * 搜索建议城市（基于缓存历史）
   * @param {string} query - 搜索查询
   * @returns {Array<string>} 建议的城市列表
   */
  getSuggestedCities(query) {
    if (!query || query.trim().length === 0) {
      return this.getCachedCities().slice(0, 5); // 返回最近的5个城市
    }
    
    const cachedCities = this.getCachedCities();
    const queryLower = query.toLowerCase().trim();
    
    return cachedCities.filter(city => 
      city.toLowerCase().includes(queryLower)
    ).slice(0, 5);
  }
}

// 创建单例实例
const weatherManager = new WeatherManager();

export default weatherManager;